import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  // 根路径重定向去登录页
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home',
    children: [
      {
        // 主页
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        // 文章分类
        path: '/art-cate',
        component: () => import('@/views/article/Category')
      },
      {
        // 文章列表
        path: 'art-list',
        component: () => import('@/views/article/ArtList')
      },
      {
        // 基本资料
        path: 'user-info',
        component: () => import('@/views/users/UserInfo')
      },
      {
        // 更换头像
        path: '/user-avatar',
        component: () => import('@/views/users/UserAvatar')
      },
      {
        // 重置密码
        path: 'user-pwd',
        component: () => import('@/views/users/UserPwd')
      }
    ]
  },
  {
    path: '/reg',
    // webpack提供的import函数---懒加载路由
    component: () => import('@/views/register')
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  }
]

const router = new VueRouter({
  routes
})

// 白名单：无需登录就能访问的地址
const whiteList = ['/login', '/reg']

router.beforeEach((to, from, next) => {
  // console.log(to, from)
  const token = store.state.token
  // 如果没有登录
  if (!token) {
    // 且访问的是白名单地址(登录页、注册页)
    if (whiteList.includes(to.path)) {
      // 则放行
      next()
    } else {
      // 未登录却想访问其他页面，则强制进入登录页
      next('/login')
    }
  } else {
    next()
  }
})

export default router
